<template>
  <div class="bookkeeping-records">
    <h1>用户账本记录</h1>

    <!-- 添加按钮 -->
    <div class="add-record-container">
      <el-button type="success" @click="showAddForm = true">添加新账本记录</el-button>
    </div>

    <!-- 搜索并添加删除按钮 按钮和筛选条件 -->
    <div class="search-container">
      <el-input
          v-model="searchQuery"
          placeholder="搜索分类或描述"
          style="width: 300px; margin-right: 10px"
          clearable
      />
      <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="margin-right: 10px"
      />
      <el-input-number
          v-model="minAmount"
          placeholder="最小金额"
          style="margin-right: 10px"
      />
      <el-input-number
          v-model="maxAmount"
          placeholder="最大金额"
          style="margin-right: 10px"
      />
      <el-button type="primary" @click="applyFilters">应用筛选</el-button>
    </div>

    <!-- 记录列表 -->
    <div v-if="filteredRecords.length === 0" class="no-records">
      <p>没有找到符合条件的账本记录</p>
    </div>
    <table v-else>
      <thead>
      <tr>
        <th>ID</th>
        <th>类型</th>
        <th>金额（元）</th>
        <th>分类</th>
        <th>记账时间</th>
        <th>描述</th>
        <th>添加时间</th>
        <th>更新时间</th>
        <th>选项</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="record in filteredRecords" :key="record.id">
        <td>{{ record.id }}</td>
        <td>{{ record.type === 0 ? '收入' : '支出' }}</td>
        <td>{{ record.price }}</td>
        <td>{{ record.category }}</td>
        <td>{{ record.bookDate }}</td>
        <td>{{ record.remark }}</td>
        <td>{{ record.addTime ? record.addTime.replace('T', ' ') : '' }}</td>
        <td>{{ record.updateTime ? record.updateTime.replace('T', ' ') : '' }}</td>
        <td>
          <el-button type="warning" size="small" @click="openModifyForm(record)">更改</el-button>
          <el-button type="danger" size="small" @click="deleteRecord(record.id)">删除</el-button>
        </td>
      </tr>
      </tbody>
    </table>

    <!-- 返回按钮 -->
    <div class="back-button">
      <el-button @click="goBack">返回</el-button>
    </div>
  </div>

  <!-- 添加记录对话框 -->
  <el-dialog
      v-model="showAddForm"
      title="添加新账本记录"
      width="50%"
      :before-close="handleAddDialogClose"
  >
    <el-form :model="newRecord" ref="recordForm" label-width="100px">
      <el-form-item label="类型">
        <el-select v-model="newRecord.type" placeholder="请选择类型">
          <el-option label="收入" :value="0"></el-option>
          <el-option label="支出" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="记账日期">
        <el-date-picker v-model="newRecord.bookDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="选择日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="分类">
        <el-input v-model="newRecord.category" placeholder="输入分类"></el-input>
      </el-form-item>
      <el-form-item label="金额">
        <el-input-number v-model="newRecord.price" :min="0.01" :precision="2"></el-input-number>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="newRecord.remark" placeholder="输入描述"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showAddForm = false">取消</el-button>
        <el-button type="primary" @click="submitNewRecord">提交</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 修改记录对话框 -->
  <el-dialog
      v-model="showModifyForm"
      title="修改账本记录"
      width="50%"
      :before-close="handleModifyDialogClose"
  >
    <el-form :model="currentEditRecord" ref="modifyForm" label-width="100px">
      <el-form-item label="类型">
        <el-select v-model="currentEditRecord.type" placeholder="请选择类型">
          <el-option label="收入" :value="0"></el-option>
          <el-option label="支出" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="记账日期">
        <el-date-picker v-model="currentEditRecord.bookDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="选择日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="分类">
        <el-input v-model="currentEditRecord.category" placeholder="输入分类"></el-input>
      </el-form-item>
      <el-form-item label="金额">
        <el-input-number v-model="currentEditRecord.price" :min="0.01" :precision="2"></el-input-number>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="currentEditRecord.remark" placeholder="输入描述"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showModifyForm = false">取消</el-button>
        <el-button type="primary" @click="submitModifyRecord">提交修改</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

const route = useRoute();
const router = useRouter();

const bookkeepingRecords = ref([]);
const filteredRecords = ref([]);
const searchQuery = ref('');
const dateRange = ref([]);
const minAmount = ref(null);
const maxAmount = ref(null);
const token = localStorage.getItem('token');
const showAddForm = ref(false);
const showModifyForm = ref(false);
const axiosInstance = axios.create({
  baseURL: 'http://localhost:8080/api/admin',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  }
});
const newRecord = ref({
  type: 1,
  bookDate: new Date().toISOString().split('T')[0],
  category: '',
  price: 0.00,
  remark: ''
});
const currentEditRecord = ref(null);

// 获取账本记录
const fetchBookkeepingRecords = async () => {
  try {
    const response = await axiosInstance.get(`/users/${route.params.account}/bookkeeping`);
    if (response.data.success) {
      bookkeepingRecords.value = response.data.data || [];
      filteredRecords.value = [...bookkeepingRecords.value];
    } else {
      ElMessage.error(response.data.message || '获取账本记录失败');
    }
  } catch (error) {
    console.error('Error fetching bookkeeping records:', error);
    ElMessage.error('获取账本记录失败，请检查后重试');
  }
};

// 提交新记录
const submitNewRecord = async () => {
  try {
    const response = await axiosInstance.post(
        `/users/${route.params.account}/bookkeeping`,
        newRecord.value
    );

    if (response.data.success) {
      ElMessage.success('账本记录添加成功');
      await fetchBookkeepingRecords();
      newRecord.value = {
        type: 1,
        bookDate: new Date().toISOString().split('T')[0],
        category: '',
        price: 0.00,
        remark: ''
      };
      showAddForm.value = false;
    } else {
      ElMessage.error(response.data.message || '添加账本记录失败');
    }
  } catch (error) {
    console.error('Error adding bookkeeping record:', error);
    ElMessage.error('添加账本记录失败，请检查后重试');
  }
};

// 打开修改表单
const openModifyForm = (record) => {
  currentEditRecord.value = { ...record };
  showModifyForm.value = true;
};

// 提交修改记录
const submitModifyRecord = async () => {
  if (!currentEditRecord.value) return;

  try {
    const response = await axiosInstance.put(
        `/users/${route.params.account}/bookkeeping/${currentEditRecord.value.id}`,
        currentEditRecord.value
    );

    if (response.data.success) {
      ElMessage.success('账本记录修改成功');
      await fetchBookkeepingRecords();
      showModifyForm.value = false;
    } else {
      ElMessage.error(response.data.message || '修改账本记录失败');
    }
  } catch (error) {
    console.error('Error modifying bookkeeping record:', error);
    ElMessage.error('修改账本记录失败，请检查后重试');
  }
};

// 删除账本记录
const deleteRecord = (recordId) => {
  ElMessageBox.confirm(
      '确定要删除这条账本记录吗？此操作不可逆。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      const response = await axiosInstance.delete(
          `/users/${route.params.account}/bookkeeping/${recordId}`
      );

      if (response.data.success) {
        ElMessage.success('账本记录删除成功');
        await fetchBookkeepingRecords();
      } else {
        ElMessage.error(response.data.message || '删除账本记录失败');
      }
    } catch (error) {
      console.error('Error deleting bookkeeping record:', error);
      ElMessage.error('删除账本记录失败，请检查后重试');
    }
  }).catch(() => {
    ElMessage.info('已取消删除操作');
  });
};

// 页面加载时初始化
onMounted(() => {
  if (!token) {
    console.error('未找到认证令牌，请先登录');
    return;
  }
  fetchBookkeepingRecords();
});

// 应用筛选条件
const applyFilters = () => {
  filteredRecords.value = bookkeepingRecords.value.filter(record => {
    const matchesSearch = record.remark.includes(searchQuery.value) ||
        record.category.includes(searchQuery.value);
    const matchesDate = !dateRange.value.length ||
        (new Date(record.bookDate) >= new Date(dateRange.value[0]) &&
            new Date(record.bookDate) <= new Date(dateRange.value[1]));
    const matchesAmount = (!minAmount.value || record.price >= minAmount.value) &&
        (!maxAmount.value || record.price <= maxAmount.value);
    return matchesSearch && matchesDate && matchesAmount;
  });
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 关闭添加对话框
const handleAddDialogClose = () => {
  showAddForm.value = false;
  newRecord.value = {
    type: 1,
    bookDate: new Date().toISOString().split('T')[0],
    category: '',
    price: 0.00,
    remark: ''
  };
};

// 关闭修改对话框
const handleModifyDialogClose = () => {
  showModifyForm.value = false;
  currentEditRecord.value = null;
};
</script>

<style scoped>
.bookkeeping-records {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

.add-record-container {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
  gap: 10px;
}

.no-records {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  margin: 20px 0;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #ebeef5;
  padding: 12px 10px;
  text-align: left;
}

th {
  background-color: #f5f7fa;
  color: #909399;
  font-weight: bold;
}

tr:nth-child(even) {
  background-color: #f9fafc;
}

.back-button {
  margin-top: 20px;
  text-align: center;
}
</style>